package com.fingard.dsp.bank.directbank.cib02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.cib02.utils.RSA;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;

import javax.xml.namespace.QName;
import java.util.Date;

/**
 * @author Parker on 2019-11-18.
 * @version 1.0
 */
public class CIB02Base extends DirectBase {
    protected static TransIDHelper idHelper = new TransIDHelper(1,9999);

    protected String getQryTransID(){
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter) throws Exception{
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\" standalone=\"yes\"?>");

    }

    /**
     * 发送银行前置
     *
     * @param p_reqStr
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr,String method) throws Exception {
        String[] retStr = new String[]{"", ""};
        String tmpUrl = bankFront.serverURL;
        WriteBankLogLn("1.提交银行的地址：" + tmpUrl);
        WriteBankLogStep2("发送银行报文原文"+p_reqStr);
        //报文加密
        p_reqStr = RSA.encrypt(p_reqStr,getBankConfig().getValueAsString("publicKeyPath"),getCharset());
        WriteBankLogStep2("发送银行报文密文"+p_reqStr);

        Service service = new Service();
         String targetNamespace = "http://service.webservice.levelappro.com/";
        Call call = (Call) service.createCall();
        call.setTargetEndpointAddress(tmpUrl);
        call.setOperationName(new QName(targetNamespace,method));// WSDL里面描述的接口名称
        call.addParameter("arg0",
                org.apache.axis.encoding.XMLType.XSD_STRING,
                javax.xml.rpc.ParameterMode.IN);// 接口的参数
        call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
        String returnData = (String) call.invoke(new Object[] { p_reqStr });// 远程调用

        WriteBankLogStep3("银行返回密文："+returnData);
        if(StringHelper.hasAnyChar(returnData)){
            //报文解密
            returnData = RSA.decrypt(returnData,getBankConfig().getValueAsString("privateKeyPath"),getCharset());
            WriteBankLogStep3("银行返回原文："+returnData);
            retStr[0]="";
            String endTag = "</RESPONSE>";
            retStr[1]=returnData.substring(0,returnData.indexOf(endTag)+endTag.length());
        }else {
            retStr[0]="-1";
            retStr[1]="银行返回内容为空";
        }
        WriteBankLogStep3("银行返回原文："+retStr[1]);
        return retStr;
    }





}
